<?php 
/* $Id$ */
/**
 * @package SwfUploadComponent
 * @subpackage controllers.components
 */
class RootHandlerComponent extends Object {
    /**
     * 
     * @var $name
     */
    var $name = 'RootHandlerComponent';
    var $params = array();
    var $errorCode = null;
    var $errorMessage = null;
    var $overwrite = false;
    var $controller = null;
    /**
     * Contructor function
     * @param Object &$controller pointer to calling controller
     */
    function startup(&$controller) {
    	$this->controller = & $controller;
    	$this->Session = & $controller->Session;
    	$this->configs = & $controller->configs;

        //keep tabs on mr. controller's params
        $this->params = & $this->controller->params;
    }
    
    function chRoot($rootSessionName = 'common.root_id', $options = array()) {
    	
    	if (!isset($options['categoryName'])) {
			if (isset($this->controller->models['Category']['name'])) {
				$options['categoryName'] = $this->controller->models['Category']['name'];
			} else {
				$options['categoryName'] = 'Category';
			}
		}
		
		if (!isset($this->params['named']['root'])) {
			if (isset($this->params['named']['branche'])) {
				$this->params['named']['root'] = $this->params['named']['branche'];
			} else {
				if ($this->Session->check($rootSessionName)) {
					$this->configs['Category']['root_id'] = $this->Session->read($rootSessionName);
				}
			}
		}
		
		$this->controller->category_root_id = $this->configs['Category']['root_id'];
		
		// Set Facility as default root for category
		if (isset($this->params['named']['root'])) {
			$this->controller->{$options['categoryName']}->Behaviors->attach('Containable');
			$category_info = $this->controller->{$options['categoryName']}->find('first', array(
				'conditions'	=>	array("{$options['categoryName']}.alias"	=>	$this->params['named']['root']),
				'fields'		=>	array('id','name','alias'),
				'contain'		=>	array()
			));

			// Set Facility as default root for category

			if (count($category_info)) {
				$this->controller->category_root_id = $category_info[$options['categoryName']]['id'];
			}
			
			$this->params['named']['root'] = $category_info[$options['categoryName']]['alias'];
			
			// Nếu root được lấy từ branche, lưu root_id xuống
			if (isset($this->params['named']['branche'])) {
				$this->Session->write($rootSessionName, $this->controller->category_root_id);
				$this->Session->write('current.branche', $this->params['named']['branche']);
				$this->configs['Category']['root_id'] = $this->controller->category_root_id;
			} else {
				if ($this->Session->check('current.branche')) {
					$this->params['named']['branche'] = $this->Session->read('current.branche'); 
				} 
//				else {
//					$this->params['named']['branche'] = $this->controller->branches[0];
//				}
			}
		} else {
			$this->params['named']['root'] = '';
		}
		
    }
}
?>